/*
 * @Author: anxia.ack anchenkai@come-future.com
 * @Date: 2025-05-08 10:06:54
 * @LastEditors: anxia.ack anchenkai@come-future.com
 * @LastEditTime: 2025-05-08 10:08:12
 * @FilePath: /free-learning/src/hooks/useECharts.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import * as echarts from "echarts";
import type { EChartsOption } from "echarts";
import { onUnmounted } from "vue";

/**
 * 初始化 ECharts 实例
 * @param el - ECharts 容器元素
 * @param theme - 主题
 * @param renderer - 渲染器类型
 * @returns ECharts 实例和相关方法
 */
export function useECharts(
  el: HTMLElement,
  theme: "light" | "dark" | string = "light",
  renderer: "canvas" | "svg" = "canvas"
) {
  // 创建 ECharts 实例
  const chart = echarts.init(el, theme, {
    renderer,
    devicePixelRatio: window.devicePixelRatio,
  });

  // 自适应大小
  const resizeHandler = () => {
    chart?.resize();
  };

  window.addEventListener("resize", resizeHandler);

  // 组件卸载时清理
  onUnmounted(() => {
    chart?.dispose();
    window.removeEventListener("resize", resizeHandler);
  });

  return {
    chart,
    setOption: (option: EChartsOption) => {
      chart?.setOption(option);
    },
    resize: () => {
      chart?.resize();
    },
    getInstance: () => {
      return chart;
    },
  };
}
